import json
from typing import List, Dict

def merge_question_files(business_file: str = "business_observation_questions.json", 
                        sanwei_file: str = "sanwei_questions.json",
                        output_file: str = "merged_questions.json"):
    """
    合并两个题目文件为一个新的题库，并为每个题目添加编号
    """
    
    # 读取business文件
    with open(business_file, "r", encoding="utf-8") as f:
        business_data = json.load(f)
    
    # 读取sanwei文件
    with open(sanwei_file, "r", encoding="utf-8") as f:
        sanwei_data = json.load(f)
    
    # 合并题目
    merged_questions = []
    
    # 添加business题目
    business_questions = business_data.get("questions", [])
    for i, question in enumerate(business_questions):
        # 为business题目添加编号和complexity字段
        question["id"] = i + 1
        question["complexity"] = "基础单线索"
        merged_questions.append(question)
    
    # 添加sanwei题目
    sanwei_questions = sanwei_data.get("questions", [])
    for i, question in enumerate(sanwei_questions):
        # 为sanwei题目添加编号（从business题目之后开始）
        question["id"] = i + 1 + len(business_questions)
        merged_questions.append(question)
    
    # 创建新的metadata
    merged_metadata = {
        "total_generated": len(merged_questions),
        "successful": len([q for q in merged_questions if q.get("success", False)]),
        "success_rate": f"{len([q for q in merged_questions if q.get('success', False)]) / len(merged_questions) * 100:.1f}%" if merged_questions else "0%",
        "generated_at": sanwei_data.get("metadata", {}).get("generated_at", ""),
        "scenarios": list(set([q["scenario"] for q in merged_questions])),
        "dimensions": list(set([q["dimension"] for q in merged_questions])),
        "complexity_levels": list(set([q.get("complexity", "基础单线索") for q in merged_questions]))
    }
    
    # 创建合并后的数据结构
    merged_data = {
        "metadata": merged_metadata,
        "questions": merged_questions
    }
    
    # 保存到新文件
    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(merged_data, f, ensure_ascii=False, indent=2)
    
    print(f"合并完成！")
    print(f"Business题目数量: {len(business_questions)}")
    print(f"Sanwei题目数量: {len(sanwei_questions)}")
    print(f"合并后总题目数量: {len(merged_questions)}")
    print(f"成功题目数量: {merged_metadata['successful']}")
    print(f"成功率: {merged_metadata['success_rate']}")
    print(f"场景数量: {len(merged_metadata['scenarios'])}")
    print(f"维度数量: {len(merged_metadata['dimensions'])}")
    print(f"复杂度等级数量: {len(merged_metadata['complexity_levels'])}")
    print(f"结果已保存到: {output_file}")

if __name__ == "__main__":
    merge_question_files()